package leetcode.code1163;

import java.util.LinkedList;
import java.util.Queue;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution2 implements IDebug {

	public String lastSubstring(String s) {
		char[] cs = s.toCharArray();
		Queue<int[]> q = new LinkedList<>();
		char in = cs[0];
		q.add(new int[] { 0, 0 });
		for (int i = 1; i < cs.length; i++) {
			char c = cs[i];
			if (c > in) {
				q = new LinkedList<>();
				q.add(new int[] { i, i });
				in = c;
			} else if (c == in && c != cs[i - 1]) {
				q.add(new int[] { i, i });
			}
		}
		while (q.size() > 1) {
			Queue<int[]> next = new LinkedList<>();
			int[] cur = q.poll();
			cur[1]++;
			char c = cs[cur[1]];
			if (c == in && cs[cur[1] - 1] != in) {
				return new String(cs, cur[0], cs.length - cur[0]);
			}
			next.add(new int[] { cur[0], cur[1] });
			while (!q.isEmpty()) {
				cur = q.poll();
				cur[1]++;
				if (cur[1] == cs.length) {
					continue;
				}
				if (cs[cur[1]] > c) {
					c = cs[cur[1]];
					next = new LinkedList<>();
					next.add(new int[] { cur[0], cur[1] });
				} else if (cs[cur[1]] == c) {
					next.add(new int[] { cur[0], cur[1] });
				}
			}
			q = next;
		}
		int start = q.poll()[0];
		return new String(cs, start, cs.length - start);
	}

	@Override
	public void debug4() {
		H.compare("xxbx", this.lastSubstring("xxbbxxbx"));
		H.compare("bab", this.lastSubstring("abab"));
		H.compare("xxxiib", this.lastSubstring("xxxiiaxxxiib"));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution2 so = new Solution2();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
